package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
 * 员工信息 前端控制器
 * </p>
 *
 * @author 黑马程序员
 * @since 2022-06-06
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService emplyeeService;

    /**
     * 员工登录
     */
    @PostMapping("login")
    public R<Employee> login(HttpServletRequest req, @RequestBody Employee employee) {
        //通过页面传递的密码进行接收加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //通过页面提交的用户名进行查询数据库
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee one = emplyeeService.getOne(qw);
        //判断是否是否查询到数据
        if (one == null) {
            return R.error("用户名错误");
        }
        //密码比对，不一致返回登陆结果
        if (!one.getPassword().equals(password)) {
            return R.error("密码错误");
        }
        //查看员工状态是否可用，0不可用1可用
        if (one.getStatus() == 0) {
            return R.error("账号已经禁用");
        }
        //登陆成功 把id存入session中
        req.getSession().setAttribute("employee", one.getId());
        return R.success(one);
    }

    @PostMapping("logout")
    public R<String> logout(HttpServletRequest req) {
        //把session中的数据移除
        req.getSession().removeAttribute("employee");
        //第二种方法移除
//        req.getSession().invalidate();
        return R.success("退出成功");
    }

    //添加员工
    @PostMapping
    public R<String> save(HttpServletRequest req, @RequestBody Employee employee) {
        //打印日志
        log.info("添加员工的信息：{}", employee);
        //设置初始密码,因为上面密码加密了一次也需要加密一次
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //LocalDateTime在jdk8提供了一个新的时间类
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //因为登陆的时候id保存在了session中，需要得到她
//        Long id = (Long) req.getSession().getAttribute("employee");
//        employee.setCreateUser(id);
//        employee.setUpdateUser(id);
        emplyeeService.save(employee);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page> pageSelectByName(int page, int pageSize, String name) {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, name);

        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper();
        //判断查询是否有值
        qw.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件,通过更新时间
        qw.orderByDesc(Employee::getUpdateTime);
        //调用方法
        emplyeeService.page(pageInfo, qw);
        return R.success(pageInfo);
    }

    /**
     * 通过id修改员工信息
     *
     * @param req
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> statusById(HttpServletRequest req, @RequestBody Employee employee) {
        log.info(employee.toString());
        //修改需要更新修改人，通过你登陆的id在session中的id获取
//        Long empid = (Long) req.getSession().getAttribute("employee");
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empid);
        emplyeeService.updateById(employee);
        String msg ="修改成功";
        return R.success(msg);

    }

    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        log.info("根据员工id查询信息");
        Employee byId = emplyeeService.getById(id);
        String msg ="修改成功";
        if (byId != null) {
//            return R.updateSuccess(byId,msg);
            return R.success(byId);
        } else
            return R.error("查不到信息");

    }

}